
import express from 'express'
import { createServer } from 'http'
import { Server } from 'socket.io'
import cors from 'cors'

const app = express()
const server = createServer(app)
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
})

app.use(cors())
app.use(express.json())

// 模拟消息数据
let messages = []

// Socket.IO 连接处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id)

  // 加入聊天室
  socket.on('join-chat', (chatId) => {
    socket.join(chatId)
    console.log(`用户 ${socket.id} 加入聊天室 ${chatId}`)
  })

  // 发送消息
  socket.on('send-message', (message) => {
    console.log('收到消息:', message)
    
    // 保存消息
    messages.push(message)
    
    // 广播给聊天室的其他用户
    socket.to(message.chatId).emit('receive-message', message)
    
    // 模拟消息状态更新
    setTimeout(() => {
      io.to(message.chatId).emit('message-status', {
        messageId: message.id,
        status: 'delivered'
      })
    }, 1000)

    setTimeout(() => {
      io.to(message.chatId).emit('message-status', {
        messageId: message.id,
        status: 'read'
      })
    }, 2000)
  })

  // 正在输入状态
  socket.on('typing', (data) => {
    socket.to(data.chatId).emit('user-typing', {
      userId: data.userId,
      isTyping: data.isTyping
    })
  })

  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id)
  })
})

// REST API 路由
app.get('/api/messages/:chatId', (req, res) => {
  const { chatId } = req.params
  const chatMessages = messages.filter(msg => msg.chatId === chatId)
  res.json(chatMessages)
})

app.post('/api/messages', (req, res) => {
  const message = req.body
  messages.push(message)
  res.json({ success: true, message })
})

const PORT = process.env.PORT || 3001
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`)
})
